#include "server_remoteend.h"
#include "server_common.h"

RemoteEnd::RemoteEnd(const char *uid, const char *ip, int32_t life, DWORD msg_thread_id)
{
    //ctor
    m_life_max = life;
    m_uid_ptr = (char *) malloc (strlen(uid) + 1);
    m_ip_ptr = (char *) malloc (strlen(ip) + 1);
    if (m_uid_ptr != NULL && m_ip_ptr != NULL)
    {
        strcpy(m_uid_ptr, uid);
        strcpy(m_ip_ptr, ip);
        m_life = life;
        m_state = ONLINE;
        m_countdown_thread = CreateThread(NULL, 0, countDownEntry, (void*) this, 0, NULL);
        m_msg_thread_id = msg_thread_id;
    }
}

char* RemoteEnd::getUID()
{
    return m_uid_ptr;
}

char* RemoteEnd::getIP()
{
    return m_ip_ptr;
}

int32_t RemoteEnd::getLife()
{
    int32_t life_cached = 0;
    SuspendThread(m_countdown_thread);
    life_cached = m_life;
    ResumeThread(m_countdown_thread);
    return life_cached;
}

void RemoteEnd::updateIP(const char *ip)
{
    strcpy(m_ip_ptr, ip);
}

DWORD WINAPI countDownEntry(void* pM)
{
    RemoteEnd *re = (RemoteEnd *) pM;
    return re->countDown();
}

DWORD RemoteEnd::countDown()
{
    uint8_t cnt = 0;

    while (m_life > 0)
    {
        Sleep(CD_INTERVAL_MS);
        cnt++;
        if (cnt * CD_INTERVAL_MS >= 1000) // one second
        {
            m_life--;
            cnt = 0;
        }
    }
    // time up
    // Send message to update Thread
	m_state = OFFLINE;
	PostThreadMessageA(m_msg_thread_id, WM_TMUP, 0, (LPARAM) this);
    return 0;
}

void RemoteEnd::refresh()
{
    SuspendThread(m_countdown_thread);
    m_life = m_life_max;
    ResumeThread(m_countdown_thread);
}

RemoteEnd::~RemoteEnd()
{
    //dtor
    delete m_uid_ptr;
    delete m_ip_ptr;
}
